import React, { useState, useEffect } from 'react'
import './shop.css'
import { Select, Space, Input, Button } from 'antd';
import { Checkbox } from 'antd';
import { getShop } from '../../../request/api';
import { message, Popconfirm } from 'antd';
import type { PopconfirmProps } from 'antd';
import type { CheckboxProps } from 'antd';

interface ShopItem {
    id: number;
    title: string;
    name: string;
    price: number;
    shou: number; // 假设销量
    img: string;
    time: string; // 假设是日期时间格式
    hao: boolean; // 是否是好货
    shopda: string; // 店铺大类
    shang: boolean; // 是否上架
}
function Shop() {
    const [shopList, setShopList] = useState<ShopItem[]>([]);
    const [filteredShopList, setFilteredShopList] = useState<ShopItem[]>([]);
    const [storeName, setStoreName] = useState<string>('');
    const [productName, setProductName] = useState<string>('');
    const [isGoodProduct, setIsGoodProduct] = useState<string>('');
    const [isshopda, setIsshopda] = useState<string>('');
    const [loading, setLoading] = useState<boolean>(false);
    const [page, setPage] = useState<number>(1);
    const [hasMore, setHasMore] = useState<boolean>(true);
    const [selectedItems, setSelectedItems] = useState<{ id: number; checked: boolean }[]>([]);
    const [allSelected, setAllSelected] = useState<boolean>(false);
    const pagesize = 10; // 每页数量
    let loadingTimeout: NodeJS.Timeout | null = null; // 用于存储 timeout 的 ID
    const [loadingMore, setLoadingMore] = useState<boolean>(false);
    const [searchQuery, setSearchQuery] = useState<string>('');

    const handleChange = (value: string) => {
        console.log(`selected ${value}`);
    };
    const onChange: CheckboxProps['onChange'] = (e) => {
        console.log(`checked = ${e.target.checked}`);
    };

    // useEffect(() => {
    //     getShop().then(res => {
    //         // console.log(res.data.list,'shop')
    //         setShopList(res.data.list)
    //         setFilteredShopList(res.data.list);
    //     })
    // }, [])

    useEffect(() => {
        fetchShops();
    }, [page]);

    const fetchShops = async () => {
        if (loading || !hasMore) return;// 如果正在加载或没有更多数据，直接返回

        setLoading(true);
        try {
            const res = await getShop({  page });// 请求数据，传递当前页码
            const newShops = res.data.list;
            // 更新状态，将新数据添加到现有数据中
            setShopList(prev => [...prev, ...newShops]);
            setFilteredShopList(prev => [...prev, ...newShops]);

            if (newShops.length < pagesize) {
                setHasMore(false); // 没有更多数据了
            }
        } catch (error) {
            console.error('Error fetching shops:', error);
        } finally {
            setLoading(false);
        }
    };

    // 监听页面滚动
    const handleScroll = () => {
        if (loading ||!hasMore) return;

        const scrollTop = window.scrollY || document.documentElement.scrollTop;
        const windowHeight = window.innerHeight;
        const documentHeight = document.documentElement.scrollHeight;


        if (scrollTop + windowHeight >= documentHeight - 10) { // 50 px 的缓冲
            if (loadingTimeout) {
                clearTimeout(loadingTimeout); // 清除之前的 timeout
            }
              // 开始加载更多
              setLoadingMore(true);// 显示加载中的状态

            loadingTimeout = setTimeout(() => {
                setPage(prev => prev + 1); // 加载下一页
            }, 300); // 延迟 
        }
    };
    // 滚动
    useEffect(() => {
        window.addEventListener('scroll', handleScroll);
        return () => {
            window.removeEventListener('scroll', handleScroll);
            if (loadingTimeout) {
                clearTimeout(loadingTimeout); // 清除 timeout
            }
        };
    }, [loading, hasMore,loadingMore]);

    // 搜索
    const handleSearch = () => {
        setFilteredShopList(shopList.filter(item => {
            const matchesStoreName = item.name.includes(storeName);
            const matchesProductName = item.title.includes(productName);
            const matchesGoodProduct = !isGoodProduct ||
                (isGoodProduct === '好货' && item.hao === true) ||
                (isGoodProduct === '非好货' && item.hao === false);
            const matchesshopda = !isshopda || (isshopda === '哈哈' ? item.shopda === '哈哈' : item.shopda == '嘻嘻');

            return matchesStoreName && matchesProductName && matchesGoodProduct && matchesshopda;
        }));
    };
    // 清空搜索
    const delSerch = () => {
        setStoreName('');
        setProductName('');
        setIsGoodProduct('');
        setIsshopda('');
        setFilteredShopList(shopList);
    }
    // 气泡确认框
    const confirm: PopconfirmProps['onConfirm'] = (e) => {
        // console.log(e);
        message.success('删除成功');
        let index = filteredShopList.filter(item => item.id == e.id)
        filteredShopList.splice(index, 1)
        setFilteredShopList([...filteredShopList])
    };
    const cancel: PopconfirmProps['onCancel'] = (e) => {
        console.log(e);
        message.error('Click on No');
    };

    // 上架
    const Putaway = (e:any) => {
        // console.log('上架',e)
        const shopdata = filteredShopList.map(item => {
            if (item.id === e.id) {
                return { ...item, shang: !item.shang }
            }
            return item
        })
        setFilteredShopList(shopdata)
    }

    // 处理复选框的变化
    const onCheckboxChange = (id: number) => {
        setSelectedItems(prev => {
            const itemIndex = prev.findIndex(item => item.id === id);

            if (itemIndex === -1) {
                return [...prev, { id, checked: true }];
            } else {
                return prev.filter(item => item.id !== id); // 反选逻辑
            }
        });
    };
      // 全选和反选处理
      const handleSelectAll = () => {
        if (allSelected) {
            setSelectedItems([]); // 取消全选
        } else {
            const allIds = filteredShopList.map(item => item.id);
            setSelectedItems(allIds.map(id => ({ id, checked: true }))); // 全选
        }
        setAllSelected(!allSelected); // 切换全选状态
    };
    useEffect(() => {
        setAllSelected(filteredShopList.length > 0 && selectedItems.length === filteredShopList.length);
    }, [filteredShopList, selectedItems]);

    // 批量设置为好货
    const allSetGoodItems = () => {
        const updatedShopList = filteredShopList.map(item => {
            if (selectedItems.some(selected => selected.id === item.id)) {
                return { ...item, hao: true };  // 设置为好货
            }
            return item;
        });
        setFilteredShopList(updatedShopList);
        setSelectedItems([]); // 清空选中状态
    };
    // 单个设置好货
    const SetGoodItem = (item:any) => {
        const updatedShopList = filteredShopList.map(shopItem => {
            if (shopItem.id === item.id) {
                return { ...shopItem, hao: true };
            }
            return shopItem;
        });
        setFilteredShopList(updatedShopList);
        setSelectedItems([]);
    };

    return (
        <div className='shop_box'>
            <div className='shop_top'>
                <h3>
                    商品管理
                </h3>
                <div className='shop_search'>
                    <div>商品大类:
                        <Select
                            defaultValue="请选择大类"
                            style={{ width: 120 }}
                            onChange={value => setIsshopda(value)}
                            value={isshopda}
                            options={[
                                { value: '', label: '所有' },
                                { value: '哈哈', label: '哈哈' },
                                { value: '嘻嘻', label: '嘻嘻' },
                            ]}
                        />
                    </div>
                    <div>商品小类:
                        <Select
                            defaultValue="请选择小类"
                            style={{ width: 120 }}
                            onChange={handleChange}
                            options={[
                                { value: 'jack', label: 'Jack' },
                                { value: 'lucy', label: 'Lucy' },
                            ]}
                        />
                    </div>
                    <div>曝光类型:
                        <Select
                            defaultValue="全部"
                            style={{ width: 120 }}
                            onChange={handleChange}
                            options={[
                                { value: 'jack', label: 'Jack' },
                                { value: 'lucy', label: 'Lucy' },
                                { value: 'Yiminghe', label: 'yiminghe' },
                                { value: 'disabled', label: 'Disabled', disabled: true },
                            ]}
                        />
                    </div>
                    <div>好货设置:
                        <Select
                            defaultValue="好货"
                            style={{ width: 120, marginRight: 10 }}
                            onChange={value => setIsGoodProduct(value)}
                            value={isGoodProduct}
                            options={[
                                { value: '', label: '所有' },
                                { value: '好货', label: '好货' },
                                { value: '非好货', label: '非好货' },
                            ]}
                        />
                        <Select
                            defaultValue="所有分组"
                            style={{ width: 120 }}
                            onChange={handleChange}
                            options={[
                                { value: 'jack', label: 'Jack' },
                                { value: 'lucy', label: 'Lucy' },
                                { value: 'Yiminghe', label: 'yiminghe' },
                                { value: 'disabled', label: 'Disabled', disabled: true },
                            ]}
                        />
                    </div>退货类型:
                    <Select
                        defaultValue="请选择退款类型"
                        style={{ width: 150 }}
                        onChange={handleChange}
                        options={[
                            { value: '退货退款', label: '退货退款' },
                            { value: '仅退款', label: '仅退款' },
                            { value: '', label: '所有' },
                        ]}
                    />
                    <div>
                        店铺名称:<Input
                            value={storeName}
                            onChange={e => setStoreName(e.target.value)}
                            placeholder="请输入店铺名称"
                            style={{ width: 200 }} />
                    </div>
                    <div>
                        商品名称:<Input
                            value={productName}
                            onChange={e => setProductName(e.target.value)}
                            style={{ width: 200 }} />
                    </div>
                </div>
                <Button type="primary" onClick={handleSearch}>搜索</Button>
                <Button onClick={delSerch}>清空筛选条件</Button>
                <Button>设置模板</Button>
            </div>

            <div className='shop_table'>
                <div className='shop_all'>
                    <p>
                        <Checkbox checked={allSelected} onClick={handleSelectAll} />
                        全选
                    </p>
                    <Button
                        onClick={allSetGoodItems}>
                        批量设置为好货
                    </Button>
                </div>
                <div className='stab_title'>
                    <p>商品详情</p>
                    <p>价格</p>
                    <p>销量</p>
                    <p>店铺</p>
                    <p>创建时间</p>
                    <p>操作</p>
                </div>
                {
                    filteredShopList.map(item => (
                        <div key={item.id} className='shop_item'>
                            <Checkbox
                                onChange={() => onCheckboxChange(item.id)}
                                checked={selectedItems.some(selected => selected.id === item.id)}
                            />
                            <div className='shop_img'>
                                <dl>
                                    <dt>
                                        <img src={item.img} alt='' />
                                    </dt>
                                    <dd>
                                        <p>{item.title}</p>
                                        <p className='simg_info'>
                                            <span>产地:台湾</span>
                                            <span>规格:10.00公斤/箱</span>
                                            <span>特性:其他</span>
                                            <span>{item.shopda}</span>
                                        </p>
                                        <p style={{ margin: '10px', color: 'red' }}>
                                            {item.hao ? '好货' : '非好货'}
                                        </p>
                                    </dd>
                                </dl>
                            </div>

                            <div>
                                <p>￥{item.price}</p>
                            </div>
                            <div>
                                <p>{item.shou}</p>
                            </div>
                            <div>
                                <p>{item.name}</p>
                            </div>
                            <div>
                                <p>{item.time}</p>
                            </div>
                            <div>
                                <button onClick={()=>SetGoodItem(item)}>设为好货</button>
                                <button onClick={() => Putaway(item)}>
                                    {item.shang ? '上架' : '下架'}
                                </button>
                                <Popconfirm
                                    title="确定删除"
                                    description="您确定删除此商品吗?"
                                    onConfirm={() => confirm(item)}
                                    onCancel={cancel}
                                    okText="Yes"
                                    cancelText="No"
                                >
                                    <button>删除</button>
                                </Popconfirm>
                            </div>
                        </div>
                    ))
                }
                 {(loading || loadingMore) && <div>正在加载更多...</div>} {/* 加载状态 */}
                {!hasMore && <div>没有更多数据了</div>} {/* 没有更多数据提示 */}
            </div>
        </div>
    )
}

export default Shop